﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace AP_GestArm
{
    public struct field
    {
        public string Field;
        public string Value;
    }

    public delegate void SearchContextChangedHandler(List<field> fields);

    public partial class frmPrincipal : Form
    {
        #region Declarações

        DataTable dt;
        DataView dv;
        DataGridViewPrinter MyDataGridViewPrinter;
        public static int myCounter;
        public static DataGridView Grid;
        frmSearch _frmSearch;
        private string _textFilters;

        #endregion

        public frmPrincipal()
        {
            InitializeComponent();
            Text = Application.ProductName + " " + Application.ProductVersion;            
            KeyDown += new KeyEventHandler(frmPrincipal_KeyDown);
        }

        #region Fecho

        private void frmPrincipal_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("Deseja mesmo sair?", "Confirme saída", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
            { e.Cancel = true; }
        }

        private void sairToolStripMenuItem_Click(object sender, EventArgs e)
        { this.Close(); }

        #endregion

        private void frmPrincipal_Load(object sender, EventArgs e)
        {            
            #region Cria directoria DATA se esta não existir

            if (!File.Exists(Application.StartupPath + "\\Data"))
            {
                DirectoryInfo Dir = new DirectoryInfo(Application.StartupPath + "\\Data");
                Dir.Create();
            }

            #endregion

            #region DataTable

            dt = new DataTable();
            dt.Clear();
            dt.Columns.Add("Câmara", typeof(string));
            dt.Columns.Add("Zona", typeof(string));
            dt.Columns.Add("Lugar", typeof(string));
            dt.Columns.Add("Piso", typeof(string));
            dt.Columns.Add("Palete", typeof(string));
            dt.Columns.Add("Tipo Palete", typeof(string));
            dt.Columns.Add("Cód. Cliente", typeof(string));
            dt.Columns.Add("Cliente");
            dt.Columns.Add("Cód. Artigo", typeof(string));
            dt.Columns.Add("Artigo", typeof(string));
            dt.Columns.Add("Lote", typeof(string));
            dt.Columns.Add("Validade", typeof(string));
            dt.Columns.Add("Entrada", typeof(string));
            dt.Columns.Add("Quantidade");
            dt.Columns.Add("Unidade");
            dt.Columns.Add("Peso");
            dt.Columns.Add("DU");
            dt.Columns.Add("Celula", typeof(string));

            dv = new DataView(dt);

            #endregion

        }

        #region Importa Ficheiro

        private void ImportaCSV(object sender, EventArgs e)
        {            
            OpenFileDialog Abrircomo = Openfile.OpenFileD("Escolha o ficheiro de Dados a ser importado, por favor.",
                        "Comma Separated Value (*.csv)|*.csv|Text File (*.txt)|*.txt", 2);
            if (Abrircomo.ShowDialog() == DialogResult.OK)
            {
                lblFile.Text = "Ficheiro Importado: " + '"' + Abrircomo.SafeFileName + '"';

                #region Importa

                try
                {
                    DataRow row;
                    dt.Clear();
                    dt.BeginLoadData();
                    foreach (string linha in File.ReadAllLines(Abrircomo.FileName))
                    {
                        Application.DoEvents();
                        string[] arraydelinhas = linha.Split(';');
                        row = dt.NewRow();
                        row.ItemArray = arraydelinhas;
                        dt.Rows.Add(row);
                    }
                    dt.EndLoadData();
                    dv = dt.DefaultView;
                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }

                #endregion

                gridCSV.DataSource = dv;
                gridCSV.Sort(gridCSV.Columns["Celula"], System.ComponentModel.ListSortDirection.Ascending);
                gridCSV.Columns["Celula"].Visible = false;

                gridCSV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                gridCSV.Columns["Cód. Cliente"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                gridCSV.Columns["Cliente"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;

                myCounter = gridCSV.Rows.Count;
                exportarToolStripMenuItem.Enabled = true;
                btPesquisa.Enabled = true;
                btExporta.Enabled = true;

            }
        }

        #endregion

        #region Impressão
        //Manda Imprimir
        private void printToolStripButton_Click(object sender, EventArgs e)
        {
            if (SetupThePrinting())
                this.printDoc.Print();
        }

        //Configura Impressão
        private bool SetupThePrinting()
        {
            PrintDialog MyPrintDialog = new PrintDialog();
            MyPrintDialog.AllowCurrentPage = false;
            MyPrintDialog.AllowPrintToFile = false;
            MyPrintDialog.AllowSelection = false;
            MyPrintDialog.AllowSomePages = false;
            MyPrintDialog.PrintToFile = false;
            MyPrintDialog.ShowHelp = false;
            MyPrintDialog.ShowNetwork = false;

            if (MyPrintDialog.ShowDialog() != DialogResult.OK)
                return false;

            this.printDoc.DocumentName = "Report";
            this.printDoc.PrinterSettings =
                                MyPrintDialog.PrinterSettings;
            this.printDoc.DefaultPageSettings =
            this.printDoc.PrinterSettings.DefaultPageSettings;
            this.printDoc.DefaultPageSettings.Margins =
                             new Margins(40, 40, 40, 40);

            if (MessageBox.Show("Deseja Centrar?",
                "Centrar na página", MessageBoxButtons.YesNo,
                MessageBoxIcon.Question) == DialogResult.Yes)
                MyDataGridViewPrinter = new DataGridViewPrinter(this.gridCSV,
                this.printDoc, true, true, "Câmaras", new Font("Arial", 18,
                FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
            else
                MyDataGridViewPrinter = new DataGridViewPrinter(this.gridCSV,
                this.printDoc, false, true, "Câmaras", new Font("Arial", 18,
                FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);

            return true;
        }

        //Conteúdo a imprimir
        private void printDoc_PrintPage(object sender, PrintPageEventArgs e)
        {
            bool more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            if (SetupThePrinting())
            {
                PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
                MyPrintPreviewDialog.Document = this.printDoc;
                MyPrintPreviewDialog.ShowDialog();
            }
        }
        #endregion

        private void visualizarBitolasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmBitolas frmBitolas = new frmBitolas();
            frmBitolas.ShowDialog();
        }

        private void lugaresDisponToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmLocalizacoes frmLocalizacoes = new frmLocalizacoes();
            frmLocalizacoes.ShowDialog();
        }

        #region Exporta para Excel

        private void ExportaExcel(object sender, EventArgs e)
        {
            ExcelClass.OpenXls("Mapa Camaras.xls");

            #region Ve camaras existentes na grid e junta a array

            string[] Camaras = new string[] { };
            for (int i = 0; i < gridCSV.Rows.Count; i++)
            {
                if (gridCSV.Rows[i].Visible)
                {
                    string Camara = "Câmara" + gridCSV["Câmara", i].Value;
                    if (!((IList<string>)Camaras).Contains(Camara))
                    {
                        Array.Resize(ref Camaras, i + 1);
                        Camaras[i] = Camara;
                    }
                }
            }

            #endregion

            if (ExcelClass.check)
            {
                #region Mete visiveis as camaras constantes da Array Camaras e Insere Títulos

                for (int i = 2; i <= ExcelClass.xlWorkBook.Sheets.Count; i++)
                {
                    ExcelClass.xlWorkSheet = (Excel.Worksheet)ExcelClass.xlWorkBook.Worksheets.get_Item(i);
                    if (((IList<string>)Camaras).Contains(ExcelClass.xlWorkSheet.Name))
                    { ExcelClass.ShowSheet(ExcelClass.xlWorkSheet); }
                    else
                    { ExcelClass.HideSheet(ExcelClass.xlWorkSheet); }
                }

                #endregion

                #region Dá Cor às células

                this.pBar.Value = 0;
                this.pBar.Maximum = this.gridCSV.Rows.Count;
                this.pBar.Visible = true;

                for (int i = 0; i < this.gridCSV.Rows.Count; i++)
                {
                    Application.DoEvents();
                    if (this.gridCSV.Rows[i].Visible == true)
                    {
                        this.pBar.Value += 1;
                        this.pBar.Refresh();
                        int percent = (int)(((double)this.pBar.Value / (double)this.pBar.Maximum) * 100);
                        this.pBar.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)9.25, FontStyle.Regular), Brushes.Black, new PointF(this.pBar.Width / 2 - 10, this.pBar.Height / 2 - 7));

                        ExcelClass.xlWorkSheet =
                            (Excel.Worksheet)ExcelClass.xlWorkBook.Worksheets.get_Item("Câmara" + this.gridCSV["Câmara", i].Value);
                        string Celula = "Cam_" + this.gridCSV["Câmara", i].Value + "C" +
                                                 this.gridCSV["Celula", i].Value + "_" +
                                                 this.gridCSV["Piso", i].Value;

                        try
                        {
                            Excel.Range myRange = ExcelClass.xlWorkSheet.get_Range(Celula, Type.Missing );
                            myRange.AddComment(myRange.Comment +
                                "Cliente " + this.gridCSV["Cliente", i].Value + "\n"
                                + "Artigo " + this.gridCSV["Artigo", i].Value.ToString().Trim() + "\n"
                                + "Palete " + this.gridCSV["Palete", i].Value);
                            myRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(Color.LightBlue);
                        }
                        catch
                        {//TODO: MessageBox.Show(" Erro", "", MessageBoxButtons.OK, MessageBoxIcon.Stop); 
                        }
                    }
                }

                this.pBar.Visible = false;
                #endregion
            }

            ExcelClass.SaveXls(ExcelClass.xlWorkBook, "Mapa Camaras Cores.xls");
            ExcelClass.CloseXls(ExcelClass.xlWorkBook, "Mapa Camaras.xls");
            ExcelClass.OpenXls("Mapa Camaras Cores.xls");
            ExcelClass.xlApp.Visible = true;
            if (ExcelClass.Culture != null)
            {
                System.Threading.Thread.CurrentThread.CurrentCulture =
                                System.Globalization.CultureInfo.CreateSpecificCulture(ExcelClass.Culture);
            }
        }
        #endregion

        #region Encontra Lugar

        private void encontrarLugarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            InputBoxResult Input = InputBox.Show("Introduza a dimensão da Palete", "Dimensão");
            if (Input.ReturnCode == System.Windows.Forms.DialogResult.OK && Input.Text != string.Empty)
            {
                BaseDados Lugares = new BaseDados(Application.StartupPath + "\\Data\\bd.mdb");
                Lugares.Locais();

                ExcelClass.OpenXls("Mapa Camaras.xls");

                if (ExcelClass.check)
                {
                    ExcellLivres.Camaras(Lugares.d7.Tables["Lugares"]);

                    #region Dá Cor às células

                    this.pBar.Value = 0;
                    this.pBar.Maximum = Lugares.d7.Tables["Lugares"].Rows.Count;
                    this.pBar.Visible = true;

                    for (int i = 0; i < Lugares.d7.Tables["Lugares"].Rows.Count; i++)
                    {
                        Application.DoEvents();
                        this.pBar.Value += 1;
                        this.pBar.Refresh();
                        int percent = (int)(((double)this.pBar.Value / (double)this.pBar.Maximum) * 100);
                        this.pBar.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)9.25, FontStyle.Regular), Brushes.Black, new PointF(this.pBar.Width / 2 - 10, this.pBar.Height / 2 - 7));

                        ExcelClass.xlWorkSheet =
                            (Excel.Worksheet)ExcelClass.xlWorkBook.Worksheets.get_Item("Câmara" + Lugares.d7.Tables["Lugares"].Rows[i]["Camara"].ToString());
                        string Celula = "Cam_" + Lugares.d7.Tables["Lugares"].Rows[i]["Camara"].ToString() + "C" +
                                                 Lugares.d7.Tables["Lugares"].Rows[i]["Celula"].ToString() + "_" +
                                                 Lugares.d7.Tables["Lugares"].Rows[i]["Piso"].ToString();

                        if (Lugares.d7.Tables["Lugares"].Rows[i]["Ocupado"].ToString() == "Não" &&
                            Lugares.d7.Tables["Lugares"].Rows[i]["Bitola"].ToString().Trim() != "")
                        {
                            try
                            {
                                Double Dimensao = Convert.ToDouble(Input.Text);
                                Double dimBitola = Convert.ToDouble(Lugares.d7.Tables["Lugares"].Rows[i]["Bitola"]);
                                if (Lugares.d7.Tables["Lugares"].Rows[i]["Bitola"].ToString().IndexOf(",") == -1)
                                { dimBitola = Convert.ToDouble(Lugares.d7.Tables["Lugares"].Rows[i]["Bitola"]); }

                                if (dimBitola > Dimensao)
                                { ExcellLivres.TamanhoMaior(Celula); }
                                if (dimBitola == Dimensao)
                                { ExcellLivres.TamanhoCerto(Celula); }
                                if (dimBitola < Dimensao)
                                {//TODO: MessageBox.Show("Não existem lugares livres para a mercadoria","Erro"); 
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message + " , o programa irá encerrar", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                                this.Dispose();
                                Application.Exit();
                            }
                        }
                    }
                    this.pBar.Visible = false;

                    #endregion
                }

                ExcelClass.SaveXls(ExcelClass.xlWorkBook, "Mapa Lugares.xls");
                ExcelClass.CloseXls(ExcelClass.xlWorkBook, "Mapa Camaras.xls");
                ExcelClass.OpenXls("Mapa Lugares.xls");
                ExcelClass.xlApp.Visible = true;
                if (ExcelClass.Culture != null)
                {
                    System.Threading.Thread.CurrentThread.CurrentCulture =
                                System.Globalization.CultureInfo.CreateSpecificCulture(ExcelClass.Culture);
                }
            }
        }

        #endregion

        private void sobreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSobre frmSobre = new frmSobre();
            frmSobre.Show(this);
        }

        private void btPesquisa_Click(object sender, EventArgs e)
        {
            if (_frmSearch == null)
            {
                List<field> fields = new List<field>();

                for (int i = 0; i < gridCSV.Columns.Count - 1; i++)
                {
                    if (gridCSV.Columns[i].ValueType == typeof(string))
                    {
                        field f = new field {Field = gridCSV.Columns[i].Name};
                        fields.Add(f);
                    }
                }
                _frmSearch = new frmSearch(fields);
                _frmSearch.TextChanged += new SearchContextChangedHandler(searchgrid_TextChanged);
            }
            _frmSearch.ShowDialog();
        }

        private void searchgrid_TextChanged(List<field> fields)
        {
            _textFilters = ""; //reset filters
            bool first = true; //para por " and "
            foreach (field f in fields)
            {
                if (f.Value.Length > 0) //Só de houver um valor
                {
                    if (!first) _textFilters += " and ";
                    _textFilters += "[" + f.Field + "]" + " like '%" + f.Value + "%'";
                    first = false;
                }
            }
            dv.RowFilter = _textFilters;
        }

        #region ShortCuts

        private void frmPrincipal_KeyDown(object sender, KeyEventArgs e)
        {
            //keypreview do form tem de estar activo
            if (e.KeyCode == Keys.F3 && btPesquisa.Enabled)
            { btPesquisa_Click(sender, e); }
            if (e.Control && e.KeyCode == Keys.I)
            { ImportaCSV(sender, e); }
            if (e.Control && e.KeyCode == Keys.P)
            { printToolStripButton_Click(sender, e); }
        }

        #endregion

        private void lblLimparFiltros_Click(object sender, EventArgs e)
        {
            dv.RowFilter = "";
            _textFilters = "";
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        { System.Diagnostics.Process.Start("http://www.anaprog.net"); }

    }
}